﻿using System;
using QuickPrompt.DomainModel;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using QuickPrompt.DomainModel.Identity;
using RedandBlue.Common.Authorization;

namespace QuickPrompt.DataAccess
{
    public class Seed
    {
        public void Run(QuickPromptContext context)
        {
#if DEBUG
            //System.Diagnostics.Debugger.Launch();
#endif

            #region User Roles
            if (!context.Roles.Any(r => r.Name.Equals("Admin", StringComparison.OrdinalIgnoreCase)))
            {
                var role = new Role { Name = "Admin", Description = "Full access to the site"};

                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);

                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name.Equals("User", StringComparison.OrdinalIgnoreCase)))
            {
                var role = new Role { Name = "User", Description = "General access to the app"};

                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);

                manager.Create(role);
            }
            #endregion

            #region users

            var userStore = new UserStore<User>(context);
            var userManager = new UserManager<User>(userStore);
            var user = context.Users.FirstOrDefault(u => u.UserName == "hbopuri") as User;
            if (user == null)
            {
                user = new User
                {
                    UserName = "hbopuri",
                    FirstName = "Harsha",
                    LastName = "Bopuri",
                    IsAdmin = 1,
                    IsActive = true,
                    Password = "CodePlex$2015",
                };

                userManager.Create(user, "CodePlex$2015");
                userManager.AddToRole(user.Id, "Admin");
            }
            else
            {
                user.UserName = "hbopuri";
                user.FirstName = "Harsha";
                user.LastName = "Bopuri";
                user.IsAdmin = 1;
                user.IsActive = true;
                user.Password = "CodePlex$2015";
                userManager.Update(user);
            }
            List<User> users = context.Users.ToList().ConvertAll(x=> (User)x);

                //var users = GetUsers();
                //if (users.Count > 0)
                //    context.Users.AddOrUpdate(u=>u.UserName, users.ToArray());
                //context.CommitSeed();


                #endregion

                #region notes

                var notes = GetNotes(users);
                if (users.Count > 0)
                    context.QuickNotes.AddOrUpdate(n => new { n.UserGuid, n.Name}, notes.ToArray());
            context.CommitSeed();

            #endregion

            #region prompts

            var prompts = GetPrompts(context);
            if (prompts.Count > 0)
                context.Prompts.AddOrUpdate(p => new { p.NoteId, p.PromptFrequency }, prompts.ToArray());
            context.CommitSeed();

            #endregion
        }

        private List<Prompt> GetPrompts(QuickPromptContext context)
        {
            List<Prompt> prompts = new List<Prompt>();
            var demoNote = context.QuickNotes.FirstOrDefault(x => x.Name.Equals("Phone Bill", StringComparison.OrdinalIgnoreCase)
                                                     &&
                                                     x.User.UserName.Equals("hbopuri",
                                                         StringComparison.OrdinalIgnoreCase));
            if (demoNote == null)
                return null;

            string timezone = TimeZoneInfo.Local.IsDaylightSavingTime(DateTime.Now)
                ? TimeZoneInfo.Utc.DaylightName
                : TimeZoneInfo.Utc.StandardName;
            prompts.Add(new Prompt()
            {
                NoteId = demoNote.Id,
                AddressValue = "hbopuri@hotmail.com",
                PromptType =  PromptType.Email,
                PromptTimeZone = timezone,
                PromptFrequency = PromptFrequency.Daily,
                StartingFromUtc = DateTime.UtcNow,
                IsActive = true
            });
            prompts.Add(new Prompt()
            {
                NoteId = demoNote.Id,
                AddressValue = "5167493582",
                PromptType = PromptType.Text,
                PromptTimeZone = timezone,
                PromptFrequency = PromptFrequency.OneTime,
                StartingFromUtc = DateTime.UtcNow.AddMinutes(2),
                IsActive = true
            });
            prompts.Add(new Prompt()
            {
                NoteId = demoNote.Id,
                AddressValue = "5167493582",
                PromptType = PromptType.Voice,
                PromptTimeZone = timezone,
                PromptFrequency = PromptFrequency.Weekly,
                StartingFromUtc = DateTime.UtcNow.AddDays(2),
                IsActive = true
            });

            return prompts;
        }

        private List<QuickNote> GetNotes(List<User> users)
        {
            var hbopuri = users.FirstOrDefault(x => x.UserName.Equals("hbopuri", StringComparison.OrdinalIgnoreCase));
            var demoNote = new QuickNote()
            {
                Name = "Phone Bill",
                Description = "Check if you made the payment for your phone bill",
                //UserId = hbopuri.UserId,
                UserGuid = hbopuri.Id,
                StartDateUtc = DateTime.UtcNow,
                EndDateUtc = DateTime.UtcNow.AddDays(5),
                IsActive = true
            };
           
            List<QuickNote> notes = new List<QuickNote>
            {
                demoNote
            };
            return notes;
        }

        private List<User> GetUsers()
        {
            List<User> users = new List<User>();
            string password = "CodePlex$2015";
            var passwordUtil = new Password();
            var salt = passwordUtil.GenerateSalt();
            string hash = passwordUtil.EncodeToHash(password : password, salt: salt);
            users.Add(new User()
            {
                UserName = "hbopuri",
                FirstName = "Harsha",
                LastName = "Bopuri",
                IsAdmin = 1,
                IsActive = true,
                Password = password,
                PasswordSalt = salt,
                PasswordHash = hash,
            });
            return users;
        }
    }
}
